import time

import allure
import pytest
from appium import webdriver
from appium.options.common import AppiumOptions
from appium.webdriver.webdriver import WebDriver

from utils.file_util import get_path

# 定义全局变量 driver
driver: WebDriver = None

# app包名
appPackage = "com.tencent.wework"
appActivity = ".launch.LaunchSplashActivity"


@pytest.fixture(scope="class")
def app():
    global driver
    # 创建字典，存放desired capabilities
    desired_caps = {}
    # 平台名称和版本
    desired_caps['platformName'] = 'Android'
    desired_caps['platformVersion'] = '14'
    # 模拟器名称
    desired_caps['avd'] = 'Galaxy_Nexus_API_34'
    # 设备名称
    desired_caps['deviceName'] = 'emulator-5554'
    # 包名和首次打开页面名
    desired_caps['appPackage'] = appPackage
    desired_caps['appActivity'] = appActivity
    # 引擎名
    desired_caps['automationName'] = 'UiAutomator2'
    # 不清理缓存
    desired_caps['noReset'] = 'true'
    # 首次启动的时候，不停止app
    desired_caps['dontStopAppOnReset'] = 'true'
    # 跳过安装，权限设置等操作
    desired_caps['skipDeviceInitialization'] = 'true'
    # 中文输入
    desired_caps['unicodeKeyBoard'] = 'true'
    # 设置以下两个参数来控制启动app和关闭掉app
    desired_caps["appium:forceAppLaunch"] = True
    desired_caps["appium:shouldTerminateApp"] = True
    # 实例化 AppiumOptions 对象
    options = AppiumOptions().load_capabilities(desired_caps)
    # 创建driver实例
    driver = webdriver.Remote('http://localhost:4723', options=options)
    yield driver
    # 所有用例执行完毕后，退出
    driver.quit()


@pytest.fixture(scope="function", autouse=True)
def setup_and_teardown():
    """
    每个测试用例执行前启动app
    :return:
    """
    # 先退出app，再启动
    driver.terminate_app(appPackage)
    driver.activate_app(appPackage)
    yield
    driver.terminate_app(appPackage)


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    # 获取时间戳
    now_time = time.strftime('%Y_%m_%d_%H_%M_%S')
    # 配置截图和 page source 路径
    image_path = get_path(f"image/{now_time}.PNG")
    page_source_path = get_path(f"page_source/{now_time}_page_source.html")
    # rep.when可选参数有call、setup、teardown,
    # call表示为用例执行环节、setup、teardown为环境初始化和清理环节
    if rep.when == "call" and rep.failed:
        # 截图
        driver.save_screenshot(image_path)
        # 记录 page source
        with open(page_source_path, 'w', encoding="u8") as f:
            f.write(driver.page_source)
        # 将截图和 page source 记录到报告中
        allure.attach.file(image_path, "异常截图", allure.attachment_type.PNG)
        allure.attach.file(page_source_path, "page-source", allure.attachment_type.TEXT)



# 解决用例描述中中文乱码的问题
def pytest_collection_modifyitems(
        session, config, items
) -> None:
    for item in items:
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')


